package com.analyse.stock.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.analyse.stock.constant.ApiConstant;
import com.analyse.stock.constant.StockConstant;
import com.analyse.stock.mapper.FundFlowHistoryMapper;
import com.analyse.stock.model.FundFlowHistoryModel;
import com.analyse.stock.model.StockInfoModel;
import com.analyse.stock.service.IFundFlowHistory;
import com.analyse.stock.service.IStockInfo;
import com.analyse.stock.utils.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class FundFlowHistoryService extends ServiceImpl<FundFlowHistoryMapper, FundFlowHistoryModel> implements IFundFlowHistory {

    @Autowired
    private IStockInfo istockInfo;

    @Override
    public void pullFundFlowHistory(String stockCode,Integer lmt){
        Set<String> sets = Sets.newHashSet();
        if(StringUtils.isNotBlank(stockCode)){
            sets.add(stockCode);
        }
        List<StockInfoModel> stockList = istockInfo.getStockList(sets);
        if(CollUtil.isEmpty(stockList)){
            return;
        }
        Date beginDate = DateUtil.offsetDay(new Date(),lmt);
        for(StockInfoModel stockModel : stockList) {
            List<FundFlowHistoryModel> hisModes = baseMapper.getFundFlowHistoryByModel(FundFlowHistoryModel.me(stockModel.getStockCode(),beginDate));
            if(CollUtil.isNotEmpty(hisModes) && (hisModes.size()==lmt || lmt ==0)){
                continue;
            }
            long time = System.currentTimeMillis()*1001;
            String url = StrUtil.format(ApiConstant.FUND_FLOW_URL,lmt,String.format("%s.%s",stockModel.getMarkCode(), stockModel.getStockCode()),time);
            String result2 = HttpUtil.sendGet(url, "*/*", StockConstant.UTF8, 6000L);
            if (StringUtils.isBlank(result2)) {
                continue;
            }
            JSONObject object2 = JSON.parseObject(result2);
            if (Objects.isNull(object2) || Objects.isNull(object2.getJSONObject("data")) ||
                    StringUtils.isBlank(object2.getJSONObject("data").getString("klines"))) {
                log.info("## 股票:{}, {} 没有近{}的 资金流向数据-----",
                        stockModel.getStockCode(),stockModel.getStockName(),lmt==0?"半年":String.format("%s天",lmt));
                continue;
            }
            log.info("## 股票:{}, {} 开始解析 近{}的资金流向数据-----",
                    stockModel.getStockCode(),stockModel.getStockName(),lmt==0?"半年":String.format("%s天",lmt));
            JSONArray array2 = JSON.parseArray(object2.getJSONObject("data").getString("klines"));
            List<FundFlowHistoryModel> modes = Lists.newArrayList();
            for (Object vo : array2) {
                String[] str = vo.toString().split(StrUtil.COMMA);
                FundFlowHistoryModel model = FundFlowHistoryModel.transFundFlowHistoryModel(str, stockModel.getStockCode());
                if (Objects.nonNull(model)) {
                    modes.add(model);
                }
            }
            try{
                super.saveBatch(modes);
                //更新主力每日 平均净增加/减少 股本数
                baseMapper.updateAvgCapital(stockModel.getStockCode());
            }catch (Exception ex){
                log.error("### 唯一键冲突，不进行处理，自动舍弃数据，result：{}",result2);
            }
        }
    }

    @Override
    public List<FundFlowHistoryModel> getFundFlowHistoryList(String stockCode, String startDate){
        LambdaUpdateWrapper<FundFlowHistoryModel> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(FundFlowHistoryModel::getStockCode,stockCode);
        wrapper.ge(FundFlowHistoryModel::getTradeDate,startDate);
        List<FundFlowHistoryModel> list = super.list(wrapper);
        if(CollUtil.isEmpty(list)){
            return Lists.newArrayList();
        }
        //升序排列
        return list.stream().sorted(Comparator.comparing(FundFlowHistoryModel::getTradeDate)).collect(Collectors.toList());
    }

}
